package com.berry.MedCheck;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.*;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.*;
import com.berry.MedCheck.db.UserDB;
import com.berry.MedCheck.grapy.LineEntity;
import com.berry.MedCheck.grapy.MAChart;

import java.io.UTFDataFormatException;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: Airay.Rong
 * Date: 13-12-4
 * Time: 下午1:36
 * To change this template use File | Settings | File Templates.
 */
public class DataActivity extends BaseActivity implements View.OnClickListener, DataUnpackage.DataFullCallback {
	private TextView mTVSpo2;
	private TextView mTVPrbpm;
	private TextView mTVPI;
	private ImageView mBerry;
	private MAChart machart;
	private Timer mTimerSpo2;
//	private Timer mTimerPR;
//	private Timer mTimerPI;


	private RelativeLayout mPartSpo2;
	private RelativeLayout mPartPR;
	private RelativeLayout mPartPI;
	private ImageButton mSearchBT;
	private BluetoothAdapter mBluetoothAdapter = null;
	private ProgressDialog progressDialog = null;

	public static final int MESSAGE_STATE_CHANGE = 1;
	public static final int MESSAGE_READ = 2;
	public static final int MESSAGE_WRITE = 3;
	public static final int MESSAGE_DEVICE_NAME = 4;
	public static final int MESSAGE_TOAST = 5;
	public static final int MESSAGE_CONNECT_FAIL = 6;
	public static final int MESSAGE_BT_CONNECT_LOSE = 7;
	public static final int MACHART_MAX_DATA_DISP = 300;

	public static final String DEVICE_NAME = "device_name";
	public static final String DEVICE_ADDRES = "device_addres";
	public static final String TOAST = "toast";
	private long mCurrentUserID;
	private BluetoothChatService mChatService = null;
	private boolean bUserCancelChooseBT = false;
	private boolean bPause = false;
	private String mConnectedDeviceName = null;
	private String mConnectedDeviceAddr = null;
	private BluetoothDevice mPairedSpo2Device = null;
	private DataUnpackage mDataUnpackage;
	private long mDBRecordTime = 0;
	private int CHART_DATA = 0;
	private boolean CHART_DATA_TO_2 = false;
	private int curSpo2Value = 0;
	private int curPRValue = 0;
	private float VALUE_WINDOW ;
	private boolean bValueWindowOpen = false;
	private int nValueWindowIndex = 0;
	private boolean bGetDataFromBT;

	private static final Boolean BT_CONNECT_SECURITY = true;
	private List<Float> MAChartValues1;
	private static final String[] PROJECTION = new String[]{
			UserDB.DBColumns._ID, // 0
			UserDB.DBColumns.USERID, // 2
			UserDB.DBColumns.DATE, // 3
			UserDB.DBColumns.SPO2, // 4
			UserDB.DBColumns.PR, // 5
			UserDB.DBColumns.PI, // 6
	};

	@Override
	protected void onPause() {
		super.onPause();
		bPause = true;
	}

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.data_activity);
		//enableHomekey();

		mTVSpo2 = (TextView) findViewById(R.id.tv_spo2);
		mTVPrbpm = (TextView) findViewById(R.id.tv_prbpm);
		mTVPI = (TextView) findViewById(R.id.tv_pl);
		mBerry = (ImageView) findViewById(R.id.berry);
		mBerry.setOnClickListener(this);
		mSearchBT = (ImageButton) findViewById(R.id.search_bt);
		mSearchBT.setOnClickListener(this);
		mPartSpo2 = (RelativeLayout) findViewById(R.id.data_spo2);
		mPartSpo2.setOnClickListener(this);
		mPartPR = (RelativeLayout) findViewById(R.id.data_pr);
		mPartPR.setOnClickListener(this);
		mPartPI = (RelativeLayout) findViewById(R.id.data_pl);
		mPartPI.setOnClickListener(this);
		dealWithNewIntent(getIntent());
		if (mCurrentUserID != 0) {
			queryUserData();
		}
		checkBtStatus();
		mChatService = new BluetoothChatService(this, mHandler);

		mDataUnpackage = new DataUnpackage(this);
		//mDataUnpackage.testSpo2Value(0X197);
		initMAChart();
		keepScreenAlwaysOn();
		setupMenuCallback();
		creatTimer();
		VALUE_WINDOW = getResources().getDimension(R.dimen.machart_value_window);
		if (VALUE_WINDOW != 0) {
			bValueWindowOpen = true;
		}
		resetTextViews(0, 0, 0, 0);
	}

	private void registeBTBondReceiver() {
		IntentFilter filter = new IntentFilter();
		filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
		registerReceiver(mBTBundReceiver, filter);
	}

	private void enableHomekey() {
		final Window window = getWindow();
		final WindowManager.LayoutParams lp = window.getAttributes();
		//if(enable)
		lp.flags |= 0x80000000;
		//else
		//	lp.flags &= ~WindowManager.LayoutParams.FLAG_HOMEKEY_DISPATCHED;
		window.setAttributes(lp);
	}

	private void creatTimer() {
		mTimerSpo2 = new Timer();
//		mTimerPR = new Timer();
//		mTimerPI = new Timer();
		startBlink(mTVSpo2);
	}


	private void setupMenuCallback() {
		mListener = new MenuCallback() {
			@Override
			public void onMenuClick(int id) {
				//do nothing
			}
		};
	}

	private void keepScreenAlwaysOn() {
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

	}

	private void loadUserLastData() {
		String selection = "userid=" + mCurrentUserID;
		Cursor mCursor = managedQuery(
				UserDB.DBColumns.MEASURE_URI,            // Use the default content URI for the provider.
				PROJECTION,                       // Return the note ID and title for each note.
				selection,                             // No where clause, return all records.
				null,                             // No where clause, therefore no where column values.
				UserDB.DBColumns.DEFAULT_MEAUSURE_SORT_ORDER  // Use the default sort order.
		);
		if (mCursor.getCount() == 0) {
			return;
		}
		mCursor.moveToFirst();
		int iSpo2 = mCursor.getColumnIndex(UserDB.DBColumns.SPO2);
		int iPr = mCursor.getColumnIndex(UserDB.DBColumns.PR);
		int iPi = mCursor.getColumnIndex(UserDB.DBColumns.PI);
		int dataSpo2 = mCursor.getInt(iSpo2);
		int dataPR = mCursor.getInt(iPr);
		float dataPI = mCursor.getInt(iPi);
		resetTextViews(dataSpo2, dataPR, dataPI, 0);
	}

	private void queryUserData() {

	}

	private void dealWithNewIntent(Intent intent) {
		if (intent == null) {
			return;
		}
		String action = intent.getAction();
		if (action == null) {
			return;
		}
		if (Utils.INTENT_ACK_SHOW_DATA.equals(action)) {
			mCurrentUserID = intent.getLongExtra(Utils.INTENT_PARA_USER_ID, 0);
			//loadUserLastData();
			return;
		}
		if (Utils.INTENT_ACK_UPDATE_DATA.equals(action)) {

			int dataSp02 = intent.getIntExtra(Utils.INTENT_PARA_SPO2, 0);
			int dataPR = intent.getIntExtra(Utils.INTENT_PARA_PR, 0);
			int dataPI = intent.getIntExtra(Utils.INTENT_PARA_PI, 0);
			long date = intent.getLongExtra(Utils.INTENT_PARA_DATE, 0);
			updateDatas(dataSp02, dataPR, dataPI, date);
			addNewDataToMAChart((int) (Math.random() * 100));

			return;
		}
		if (Utils.INTENT_ACK_CHOOSE_BT_CANCEL.equals(action)) {
			bUserCancelChooseBT = true;
			return;
		}
		if (Utils.INTENT_ACK_CHOOSE_BT_DONE.equals(action)) {
			connectDevice(intent, BT_CONNECT_SECURITY);
			return;
		}

	}

	private void startBlink(final TextView view) {
		Timer timer = null;
		if (view == mTVSpo2) {
			timer = mTimerSpo2;
		}
		assert timer != null;
		timer.schedule(new TimerTask() {
			@Override
			public void run() {
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						int color = view.getCurrentTextColor();
						switch (color) {
							case Color.WHITE:
								break;
							case Color.RED:
								view.setTextColor(Color.TRANSPARENT);
								break;
							case Color.TRANSPARENT:
								view.setTextColor(Color.RED);
								break;
							default:
						}
					}
				});

			}
		}, 500, 1000);
	}

	private void stopBlink(TextView view) {
		if (view == mTVSpo2) {
			mTimerSpo2.cancel();
		}
		view.setTextColor(Color.WHITE);
	}

	private void updateDatas(int dataSp02, int dataPR, float dataPI, long date) {
		//Log.d("BTData", "updateDatas Sp02=" + dataSp02 + ",PR=" + dataPR + ",PI=" + dataPI);
		if (curSpo2Value != dataSp02) {
			if (dataSp02 <= Utils.DATA_SPO2_MAX && dataSp02 >= Utils.DATA_SPO2_MIN) {
				mTVSpo2.setText(Integer.toString(dataSp02) + " %");
				if (dataSp02 <= 94) {
					mTVSpo2.setTextColor(Color.RED);
				} else {
					mTVSpo2.setTextColor(Color.WHITE);
				}
			}
			curSpo2Value = dataSp02;
		}

		if (curPRValue != dataPR) {
			if (dataPR <= Utils.DATA_PR_MAX && dataPR >= Utils.DATA_PR_MIN) {
				mTVPrbpm.setText(Integer.toString(dataPR) + " bpm");
				mTVPrbpm.setTextColor(Color.WHITE);
			}
			curPRValue = dataPR;
		}

		if (dataPI <= Utils.DATA_PI_MAX && dataPI >= Utils.DATA_PI_MIN) {
			mTVPI.setText(Float.toString(dataPI) + " %");
			mTVPI.setTextColor(Color.WHITE);
		}
		saveToMeasureDB(dataSp02, dataPR, dataPI, date);
	}


	private void resetTextViews(int dataSp02, int dataPR, float dataPI, long date) {
		mTVSpo2.setText("- - %");
		mTVPrbpm.setText("- - bpm");
		mTVPI.setText("- - %");
		mTVSpo2.setTextColor(getResources().getColor(R.color.white));
		mTVPrbpm.setTextColor(getResources().getColor(R.color.white));
		mTVPI.setTextColor(getResources().getColor(R.color.white));
		curSpo2Value = 0;
		curPRValue = 0;
	}


	private void saveToMeasureDB(int dataSp02, int dataPR, float dataPI, long date) {
		if (mCurrentUserID == 0) {
			return;
		}

		//数据库每30秒(DB_RECORD_WINDOW)记录一个数据。
		if (mDBRecordTime == 0) {
			mDBRecordTime = date;
		} else {
			if ((date - mDBRecordTime) < Utils.DB_RECORD_WINDOW) {
				return;
			} else {
				mDBRecordTime = date;
			}
		}
		Uri mUri = getContentResolver().insert(UserDB.DBColumns.MEASURE_URI, null);
		Cursor mCursor = managedQuery(mUri, PROJECTION, null, null, null);
		if (mCursor != null) {
			ContentValues values = new ContentValues();
			values.put(UserDB.DBColumns.USERID, mCurrentUserID);
			values.put(UserDB.DBColumns.DATE, date);
			values.put(UserDB.DBColumns.SPO2, dataSp02);
			values.put(UserDB.DBColumns.PR, dataPR);
			values.put(UserDB.DBColumns.PI, dataPI);
			try {
				getContentResolver().update(mUri, values, null, null);
			} catch (NullPointerException e) {
			}

		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (((keyCode == KeyEvent.KEYCODE_BACK) ||
				(keyCode == KeyEvent.KEYCODE_HOME))) {
			showAlertDialog_Exit(R.string.exit_info, R.string.exit);
			return false;
		}
		return super.onKeyDown(keyCode, event);
	}

	public void showAlertDialog_Exit(int msgText, int msgTitle) {
		final AlertDialog alert = new AlertDialog.Builder(this).create();
		alert.setCanceledOnTouchOutside(true);
		alert.show();

		Window window = alert.getWindow();
		window.setContentView(R.layout.my_alert_dialog);
		TextView tv = (TextView) window.findViewById(R.id.message);
		tv.setText(this.getResources().getText(msgText));
		Button btnCancel = (Button) window.findViewById(R.id.btn_cancel);
		btnCancel.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				alert.cancel();
			}
		});
		Button btnOK = (Button) window.findViewById(R.id.btn_ok);
		btnOK.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				closeBT();
				finish();
			}
		});

	}

	private void closeBT() {
		mBluetoothAdapter.disable();
	}

	@Override
	protected void onResume() {
		super.onResume();
		registeBTBondReceiver();
		bPause = false;
		machart.start();
		if (mChatService != null) {
			// Only if the state is STATE_NONE, do we know that we haven't started already
			if (mChatService.getState() == BluetoothChatService.STATE_NONE) {
				// Start the Bluetooth chat services
				mChatService.start();
				if (mPairedSpo2Device != null) {
					if (mPairedSpo2Device.getBondState() == BluetoothDevice.BOND_BONDED
							|| mPairedSpo2Device.getBondState() == BluetoothDevice.BOND_BONDING) {

					} else
					{
						Intent intent = new Intent();
						intent.putExtra(Utils.EXTRA_DEVICE_ADDRESS, mPairedSpo2Device.getAddress())
								.putExtra(Utils.EXTRA_DEVICE_NAME, mPairedSpo2Device.getName());
						connectDevice(intent, true);
					}
				}
			}
		}
		if (bUserCancelChooseBT == true) {
			bUserCancelChooseBT = false;
			return;
		}
	}

	private void checkBtStatus() {
		mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
		if (mBluetoothAdapter == null) {
			Log.e(Utils.TAG1, "mBluetoothAdapter = null");
			showBTFailDialog();
			return;
		}
		if (!mBluetoothAdapter.isEnabled()) {
			mBluetoothAdapter.enable();
		}

		Timer timer = new Timer();
		timer.schedule(new TimerTask() {
			@Override
			public void run() {
				Set<BluetoothDevice> mDevices = mBluetoothAdapter.getBondedDevices();
				if (mDevices.size() == 0) {
					Log.d(Utils.TAG1, "BT check ok. No pair device");
					startActivity(new Intent().setClass(DataActivity.this, ChooseBtActivity.class));
				} else {
					for (BluetoothDevice device : mDevices) {
						if (device.getName().equals(Utils.SPO2_DEVICE_NAME)) {
							mPairedSpo2Device = device;
						}
					}
					if (mPairedSpo2Device == null) {
						startActivity(new Intent().setClass(DataActivity.this, ChooseBtActivity.class));
					}
				}
			}
		}, 2000);
	}

	private void openBTSetting() {
		Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
		// 设置蓝牙可见性，最多300秒
		intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, Utils.BT_DISCOVER_TIME);
		startActivityForResult(intent, Utils.INTENT_RESULT_BTSETTING);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == Utils.INTENT_RESULT_BTSETTING) {
			Log.d(Utils.TAG1, "onActivityResult INTENT_RESULT_BT SETTING resultCode=" + resultCode);
			if (resultCode == Activity.RESULT_OK) {
				startActivityForResult(new Intent().setClass(this, ChooseBtActivity.class), Utils.INTENT_RESULT_BTSEARCH);
			} else {
				//showBTFailDialog();
			}
		}
		if (requestCode == Utils.INTENT_RESULT_BTSEARCH) {
			Log.d(Utils.TAG1, "onActivityResult INTENT_RESULT_BT SEARCH resultCode=" + resultCode);
			if (resultCode == Activity.RESULT_OK) {
				connectDevice(data, BT_CONNECT_SECURITY);
			} else {
				//showBTPairDialog();
			}
		}
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);    //To change body of overridden methods use File | Settings | File Templates.
//		if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
//
//		}
//		else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
//
//		}
	}

	private void showBTFailDialog() {
		AlertDialog alert = new AlertDialog.Builder(this).create();
		alert.setCanceledOnTouchOutside(false);
		alert.setMessage(this.getResources().getText(R.string.bt_must_open));
		alert.setTitle(R.string.notify);
		//alert.setIconAttribute(android.R.attr.alertDialogIcon);
		alert.setButton(DialogInterface.BUTTON_POSITIVE, this.getResources().getText(R.string.ok), new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				//openBTSetting();
			}
		});

		alert.show();
	}
	public void showAlertDialog_ReStartBTDiscovery() {
		final AlertDialog alert = new AlertDialog.Builder(this).create();
		alert.setCanceledOnTouchOutside(true);
		alert.show();

		Window window = alert.getWindow();
		window.setContentView(R.layout.my_alert_dialog);
		TextView tv = (TextView) window.findViewById(R.id.message);
		tv.setText(this.getResources().getText(R.string.restart_bt_discovery));
		Button btnCancel = (Button) window.findViewById(R.id.btn_cancel);
		btnCancel.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				alert.cancel();
			}
		});
		Button btnOK = (Button) window.findViewById(R.id.btn_ok);
		btnOK.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				machart.stop();
				startActivity(new Intent().setClass(DataActivity.this, ChooseBtActivity.class));
			}
		});

	}
	@Override
	public void onClick(View v) {
		if (v == mBerry) {
			//sendAData();
		} else if (v == mSearchBT) {
			if (bGetDataFromBT == true) {
				showAlertDialog_ReStartBTDiscovery();
			} else {
				startActivity(new Intent().setClass(DataActivity.this, ChooseBtActivity.class));
			}
		} else if (v == mPartSpo2) {
			callDialogActivity(getResources().getString(R.string.about_spo2),
					getResources().getString(R.string.about_spo2_info));

		} else if (v == mPartPR) {
			callDialogActivity(getResources().getString(R.string.about_pr),
					getResources().getString(R.string.about_pr_info));
		} else if (v == mPartPI) {
			callDialogActivity(getResources().getString(R.string.about_pi),
					getResources().getString(R.string.about_pi_info));
		}
	}

	private void callDialogActivity(String title, String msg) {
		Intent mi = new Intent();
		mi.setClass(this, DialogActivity.class);
		mi.putExtra("title", title);
		mi.putExtra("msg", msg);
		startActivity(mi);
	}

	private void sendAData() {
//		for (int i = 0; i < 100; i++) {
//			addNewDataToMAChart((int) (Math.random() * 100));
//		}
		//(int) (Math.random() * 100)
		updateDatas((int) (Math.random() * 100),250, (int) 10, System.currentTimeMillis());
		addNewDataToMAChart((int) (Math.random() * 100));


	}

	private boolean compareNewBTDevice(String name, String addr) {
		if (name.equals(mPairedSpo2Device.getName()) && addr.equals(mPairedSpo2Device.getAddress())) {
			if (mPairedSpo2Device.getBondState() == BluetoothDevice.BOND_BONDED
					|| mPairedSpo2Device.getBondState() == BluetoothDevice.BOND_BONDING) {
				return true;
			} else {

			}
		}
		return false;

	}

	private void connectDevice(Intent data, boolean secure) {
		String address = data.getExtras().getString(Utils.EXTRA_DEVICE_ADDRESS);
		String name = data.getExtras().getString(Utils.EXTRA_DEVICE_NAME);
//		if (compareNewBTDevice(name,address) == true) {
//			Toast.makeText(getApplicationContext(),
//					getResources().getString(R.string.bt_connected) + name,
//					Toast.LENGTH_SHORT)
//					.show();
//			return;
//		}

		if (progressDialog != null && progressDialog.isShowing()) {
			progressDialog.dismiss();
		}
		progressDialog = ProgressDialog.show(this, "", getString(R.string.connect_to) + name, true, true);
		// Get the BluetoothDevice object
		BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
		// Attempt to connect to the device
		mChatService.connect(device, secure);
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);    //To change body of overridden methods use File | Settings | File Templates.
		dealWithNewIntent(intent);
	}

	private final Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
				case MESSAGE_STATE_CHANGE:
					Log.i(Utils.TAG2, "MESSAGE_STATE_CHANGE: " + getBTStateString(msg.arg1));
					switch (msg.arg1) {
						case BluetoothChatService.STATE_CONNECTED:
							//setStatus(getString(R.string.title_connected_to, mConnectedDeviceName));
							//mConversationArrayAdapter.clear();
							break;
						case BluetoothChatService.STATE_CONNECTING:
							//setStatus(R.string.title_connecting);
							break;
						case BluetoothChatService.STATE_LISTEN:
						case BluetoothChatService.STATE_NONE:
							//setStatus(R.string.title_not_connected);
							break;
					}
					break;
				case MESSAGE_WRITE:
//					byte[] writeBuf = (byte[]) msg.obj;
//					// construct a string from the buffer
//					String writeMessage = new String(writeBuf);
//					mConversationArrayAdapter.add("Me:  " + writeMessage);
					break;
				case MESSAGE_READ:
					//bytes, -1, buffer
					//msg.arg1 长度   msg.arg2：-1  msg.obj：数据
					byte[] readBuf = (byte[]) msg.obj;
					// construct a string from the valid bytes in the buffer
					//String readMessage = new String(readBuf, 0, msg.arg1);
					{
						bGetDataFromBT = true;
						mDataUnpackage.getNewWork(readBuf, msg.arg1);
					}
					//mDataUnpackage.addNewByte( readBuf[0]);
					break;
				case MESSAGE_DEVICE_NAME:
					// save the connected device's name
					if (progressDialog != null && progressDialog.isShowing()) {
						progressDialog.dismiss();
					}
					mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
					mConnectedDeviceAddr = msg.getData().getString(DEVICE_ADDRES);
					Toast.makeText(getApplicationContext(),
							getResources().getString(R.string.bt_connected) + mConnectedDeviceName,
							Toast.LENGTH_SHORT)
							.show();
					break;
				case MESSAGE_TOAST:
					Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST), Toast.LENGTH_SHORT).show();
					break;
				case MESSAGE_CONNECT_FAIL:
					if (progressDialog != null && progressDialog.isShowing()) {
						progressDialog.dismiss();
					}
					Toast.makeText(getApplicationContext(),
							getResources().getString(R.string.bt_connect_fail),
							Toast.LENGTH_SHORT)
							.show();
					break;
				case MESSAGE_BT_CONNECT_LOSE:
					bGetDataFromBT = false;
					break;
			}
		}
	};

	private String getBTStateString(int arg1) {
		switch (arg1) {
			case BluetoothChatService.STATE_CONNECTED:
				return "STATE_CONNECTED";
			case BluetoothChatService.STATE_CONNECTING:
				return "STATE_CONNECTING";
			case BluetoothChatService.STATE_LISTEN:
				return "STATE_LISTEN";
			case BluetoothChatService.STATE_NONE:
				return "STATE_NONE";
		}
		return "";
	}

	@Override
	public void onDataFull() {
		int dataSpo2 = mDataUnpackage.getSpo2();
		int dataPR = mDataUnpackage.getPulseRate();
		float dataPI = mDataUnpackage.getPI();
		int dataPauleWave = mDataUnpackage.getPulseWave();
		updateDatas(dataSpo2, dataPR, dataPI, System.currentTimeMillis());
		addNewDataToMAChart(dataPauleWave);

	}

	@Override
	public void onNewData() {
		if (bPause == true) {
			return;
		}
		machart.start();
		int dataPauleWave = mDataUnpackage.getPulseWave();
		addNewDataToMAChart(dataPauleWave);
	}

	@Override
	public void onSearchTimeLong() {
	}

	@Override
	public void onSpo2Low() {
	}

	@Override
	public void onProbeError() {
		//showProbeErrorDialog();
		resetTextViews(127, 255, 15, 0);
		machart.stop();

	}

	@Override
	public void onSearchPulse() {

	}

	private void initMAChart() {
		machart = (MAChart) findViewById(R.id.machart);
		List<LineEntity> lines = new ArrayList<LineEntity>();
		initMAChartValue();
		LineEntity MA1 = new LineEntity();
		MA1.setTitle("MA1");
		MA1.setLineColor(Color.WHITE);
		MA1.setLineData(MAChartValues1);
		lines.add(MA1);

//		LineEntity MA2 = new LineEntity();
//		MA2.setTitle("MA2");
//		MA2.setLineColor(Color.WHITE);
//		MA2.setLineData(MAChartValues2);
//		lines.add(MA2);

		List<String> ytitle = new ArrayList<String>();
		ytitle.add("0");
		ytitle.add("50");
		ytitle.add("100");
		List<String> xtitle = new ArrayList<String>();
		xtitle.add(" ");

		machart.setAxisXColor(Color.TRANSPARENT);
		machart.setAxisYColor(Color.TRANSPARENT);
		machart.setBorderColor(Color.TRANSPARENT);
		machart.setAxisMarginTop(0);
		machart.setAxisMarginLeft(0);
		machart.setAxisYTitles(ytitle);
		machart.setAxisXTitles(xtitle);
		machart.setLongtitudeFontSize(10);
		machart.setLongtitudeFontColor(Color.BLACK);
		machart.setLatitudeColor(Color.TRANSPARENT);
		machart.setLatitudeFontColor(Color.BLACK);
		machart.setLongitudeColor(Color.TRANSPARENT);
		machart.setMaxValue(125);
		machart.setMinValue(0);
		machart.setMaxPointNum(MACHART_MAX_DATA_DISP);
		machart.setDisplayAxisXTitle(false);
		machart.setDisplayAxisYTitle(false);
		machart.setDisplayLatitude(true);
		machart.setDisplayLongitude(true);
		machart.setLineData(lines);
	}

	private void initMAChartValue() {
		MAChartValues1 = new LinkedList<Float>();

	}

	private void resetMAChartValue() {
		MAChartValues1.clear();
		for (int i = 0; i < MACHART_MAX_DATA_DISP; i++) {
			MAChartValues1.add((float) 0);
		}
	}

	private void addNewDataToMAChart(int newData) {
		if (newData > 100 || newData < 0) {
			return;
		}
		if (bPause == true) {
			return;
		}
		if (bValueWindowOpen == true) {
			nValueWindowIndex ++;
			if (nValueWindowIndex >= VALUE_WINDOW) {
				nValueWindowIndex = 0;
				return;
			}
		}

		CHART_DATA++;
		if (CHART_DATA >= MACHART_MAX_DATA_DISP) {
			CHART_DATA_TO_2 = !CHART_DATA_TO_2;
			CHART_DATA = 0;
			CHART_DATA++;
		}
		if (MAChartValues1.size() < MACHART_MAX_DATA_DISP) {
			MAChartValues1.add((float) newData);
		} else {
			MAChartValues1.add(CHART_DATA - 1, (float) newData);
			MAChartValues1.remove(CHART_DATA);
		}

		machart.setDivideIndex(CHART_DATA);
		machart.invalidate();
	}

	@Override
	protected void onStop() {
		unregisterReceiver(mBTBundReceiver);
		super.onStop();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (mChatService != null) {
			mChatService.stop();
		}
		System.exit(0);
	}

	public BroadcastReceiver mBTMainReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
				int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
				switch (state) {
					case BluetoothAdapter.STATE_OFF:
						break;
					case BluetoothAdapter.STATE_TURNING_ON:
						break;
					case BluetoothAdapter.STATE_ON:
						break;
					case BluetoothAdapter.STATE_TURNING_OFF:
						break;
					default:
				}
			}
		}
	};
	private BroadcastReceiver mBTBundReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
				BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
				if (device == null) {
					return;
				}
				int bondState = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR);
				if (bondState == BluetoothDevice.BOND_NONE) {
					int reason = intent.getIntExtra("android.bluetooth.device.extra.REASON", BluetoothDevice.ERROR);
					showUnbondMessage(context, device.getName(), reason);
				}
			}

		}

		private void showUnbondMessage(Context context, String name, int reason) {
			int errorMsg;

			switch (reason) {
				case 1:
					errorMsg = R.string.bluetooth_pairing_pin_error_message;
					break;
				case 2:
					errorMsg = R.string.bluetooth_pairing_rejected_error_message;
					break;
				case 4:
					errorMsg = R.string.bluetooth_pairing_device_down_error_message;
					break;
				case 5:
				case 6:
				case 7:
				case 8:
					errorMsg = R.string.bluetooth_pairing_error_message;
					break;
				default:
					return;
			}
			String message = context.getString(errorMsg, name);
			Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
		}
	};


}
